<template>
  <div  v-loading="loading">
    <el-page-header @back="goBack" content="歌曲编辑">
    </el-page-header>

    <div style="margin-left: 5%;margin-right: 5%;">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="歌曲名字" >
          <el-input v-model="form.name" placeholder="请选择歌曲名"></el-input>
        </el-form-item>
        <el-form-item label="歌手名字">
          <el-select v-model="form.singerId" placeholder="请选择歌手">
            <el-option v-for="item in songerList"
                       :label="item.nickname"
                       :value="item.singerId"
                       :key="item.id"></el-option>
          </el-select>
          <el-button type="text" @click="open">添加歌手</el-button>

        </el-form-item>
        <el-form-item label="歌曲图片">
          <el-upload
            action="http://lzyzone.top/uploadimage/image/upload/lzy"
            :on-success="uploadSucess"
            :on-preview="handlePictureCardPreview"
            :limit="1"
            :on-remove="handleRemove">
            <i v-if="!form.imageUrl" class="el-icon-plus"></i>
            <el-avatar v-if="form.imageUrl" class="applogo"  :size="60" :src="form.imageUrl" ></el-avatar>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传音源">
          <el-upload
            class="upload-demo"
            drag
            :on-preview="handlePictureCardPreviewMP3"
            :on-remove="handleRemove"
            :on-success="uploadSucessMP3"
            action="http://lzyzone.top/uploadimage/image/upload/mp3"
            :multiple="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传mp3文件，且不超过10MB</div>
          </el-upload>

          <div v-if="true">
            <aplayer autoplay
                     :showLrc="true"
                     :music="music"/>
          </div>
        </el-form-item>

        <el-form-item label="歌曲风格">
          <el-radio-group v-model="form.type">
            <el-radio v-for="(item,index) in styleList" :label="item.styleId"  :value="item.styleId" :key="item.styleId">
              {{item.styleName}}
            </el-radio>
          </el-radio-group>
          <el-button type="text" style="margin-left: 20px;" @click="openAddStyle">添加风格</el-button>
          <el-button type="text" style="margin-left: 20px;" @click="deleteStyle">删除风格</el-button>
        </el-form-item>

        <el-form-item label="歌曲描述">
          <el-input type="textarea" v-model="form.songDescription" placeholder="请输入歌曲描述"></el-input>
        </el-form-item>
        <el-form-item label="歌 词" >
          <el-input type="textarea"   v-model="form.lyric" placeholder="请输入歌词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">OK</el-button>
          <el-button  @click="goBack">cancel</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<script>
import Aplayer from 'vue-aplayer'
import {getPromise} from '../../api/api'

export default {
  name: "songEdit",
  components: {Aplayer},
  data() {
    return {
      loading: false,
      music: {},
      styleList: [],
      songerList: [],
      form: {
        imageUrl: '',
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: 1,
        lyric: '',
        resource: '',
        songUrl: '',
        desc: ''
      }
    }
  },
  watch: {
    form: {
      deep: true,
      handler(val) {
        console.log(val)
        this.music = {
          title: this.form.name,
          artist: this.getArt, // 过滤
          src: this.form.songUrl,
          pic: this.form.imageUrl,
          lrc: this.form.lyric
        }
      }
    }
  },
  async  mounted() {
    this.loading = true;
    this.getSongerList();
    console.log(1);
    await this.initSongAndStyle();
    console.log(3);
    this.form.type = parseInt(this.form.type);
    // setTimeout(()=>{
    //   console.log("一秒后执行一次");
      this.loading = false;
    // }, 1500);
  },
  computed: {
    getImageUrl() {
      return this.form.imageurl;
    },

    getArt() {
      let obj = this.songerList.find((item) => {
        return item.singerId == this.form.singerId
      });
      return obj?obj.nickname:'未知';
    }
  },

  methods: {

    /*根据歌曲id查询，并进行初始化*/
    async initSongAndStyle() {
      let res1 = await getPromise('/sys/style'); //.get('/sys/style')
      this.styleList = res1.data.data;
      console.log(this.styleList);
      console.log(2 + "===> " + this.$route.params.songId);
      let res2 = await getPromise(`/sys/song/${this.$route.params.songId}`);
      this.form = res2.data.data;
    },

    /*获取所有歌手*/
    getSongerList() {
      this.$axios.get('/SongServlet?method=queryDataSonger')
        .then((res)=> {
          console.log(res);
          this.songerList = res.data.data;
        })
    },

    /*提交修改*/
    onSubmit() {
      console.log('submit!');
      let ans = {...this.form};
      // this.form.createTime = null;
      // this.form.updateTime = null;
      this.form.singerId = 1;
      this.$axios.post('/sys/song/update', this.form)
        .then((res)=> {
          this.goBack();
        })
    },

    goBack() {
      console.log('go back');
      // this.$parent.showSongMain = true; ///Song/info
      this.$router.push({path: '/Song/info'});
    },

    /*图片上传开始api*/
    /**/
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.form = {...this.form};
      this.form.imageUrl = null;
    },
    handlePictureCardPreview(file) {
      this.form.imageUrl = file.url;
    },
    /*上传成功的钩子*/
    uploadSucess(response, file, fileList) {
      // this.form.imageUrl = response.data.filePath;
      // console.log(this.form.imageUrl)
      this.form.imageUrl = response.data.filePath;
    },
    /*图片上传结束api*/

    /*MP3上传开始api*/
    handleRemoveMP3(file, fileList) {
      console.log(file, fileList);
      this.form = {...this.form};
      this.form.songUrl = null;
    },
    handlePictureCardPreviewMP3(file) {
      this.form.songUrl = file.url;
    },
    /*上传成功的钩子*/
    uploadSucessMP3(response, file, fileList) {
      // this.form.imageUrl = response.data.filePath;
      // console.log(this.form.imageUrl)
      console.log("-=================--");
      console.log(response);
      this.form.songUrl = response.data.filePath;
    },
    /*MP3上传结束api*/

    /*添加歌手*/
    open() {
      this.$prompt('请输入歌手', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        // 请求添加后，返回当前添加的歌手id，并将其在下拉框中选择。
        //
        this.$axios.get('/SongServlet?method=addSonger',{params: {
            name: value
          }})
          .then((res)=> {
            let id = res.data.data;
            this.$message({
              type: 'success',
              message: `添加${value}成功`
            });

            this.$axios.get('/SongServlet?method=queryDataSonger')
              .then((res)=> {
                this.songerList = res.data.data;
                this.form.type = id;
              })
          })
          .catch((err)=> {

          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `添加失败`
        });
      });
    },

    /*添加风格*/
    openAddStyle() {
      this.$prompt('请输入添加的风格', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        console.log("风格名字：" + value);
        let style = {
          "styleName": value
        }
        this.$axios.post('/sys/style',style)
          .then((res)=> {
            let id = res.data.data; // 添加的风格id
            this.$message({
              type: 'success',
              message: `添加风格${value}成功`
            });

            this.$axios.get('/sys/style')
              .then((res)=> {
                this.styleList = res.data.data;
                // this.form.type = id;
              })
          })
      }).catch(() => {
        this.$message({type: 'info', message: `添加失败`});
      });
    },
    /*获取删除的风格的名字*/
    getStyleName() {
      console.log(this.form.type)
      let ans = '';
      this.styleList.forEach(e=> {
        console.log(e)
        if(e.styleId == this.form.type) {
          ans =  e.styleName;
        }
      })
      console.log(ans)
      return ans;
    },

    /*删除风格*/
    deleteStyle() {
      this.$confirm('此操作将永久删除"'+ this.getStyleName()+'"风格, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/sys/style/' + this.form.type)
          .then((res)=> {
            this.$message({
              type: 'success',
              message: `删除风格${this.getStyleName()}成功`
            });

            this.$axios.get('/sys/style')
              .then((res)=> {
                this.styleList = res.data.data;
              })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>
.el-form {
  margin-top: 10px;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (prefers-reduced-motion: no-preference) {
  .applogo {
    animation: App-logo-spin infinite 10s linear;
  }
}
</style>
